﻿using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UI_Skill : MonoBehaviour,IBeginDragHandler, IDragHandler, IEndDragHandler,IPointerEnterHandler, IPointerExitHandler
{


	public Text text;
	public Image mask;
	public GameObject light_skill;
	private Image icon;
	private Character master;
	private Skill skill;

	private Vector3 beforpos;
	private RectTransform parentRectTransform;
	/// <summary>
    /// 用于event trigger对自身检测的开关
    /// </summary>
    private CanvasGroup canvasGroup;

	

	public void use()
	{
		if (skill != null) 
		{
			master.use_skill(skill);
		}
		
	}
	public void set_skill(Character sc, Skill skill)
	{
		this.skill = skill;
		int num = Random.Range(1,4); // 获得对应的图标
        Sprite sp = Resources.Load<Sprite>("icon/item"+num.ToString("G"));
        icon.overrideSprite = sp;
		master = sc;
	}

	// Use this for initialization
	void Start ()
	{
		skill = null;
		master = null;
		light_skill.SetActive(false);
		icon = GetComponent<Image>();
		text = GetComponentInChildren<Text>();

		parentRectTransform = transform.parent as RectTransform;
		canvasGroup = GetComponent<CanvasGroup>();
	}
	
	// Update is called once per frame
	void Update ()
	{

		if (skill != null) 
		{
			if (!skill.useful) 
			{
				mask.fillAmount -= (Time.deltaTime/skill.cd_time);
				text.text = (skill.cd_time * mask.fillAmount).ToString("#0.0") + " ";
			}
			else
			{
				mask.fillAmount = 0;
				text.text = "";
			}
		}
	}
	public void OnBeginDrag(PointerEventData eventData)
	{
		canvasGroup.blocksRaycasts = false;
		transform.SetAsLastSibling();
		beforpos = (transform as RectTransform).position;
	}
	public void OnDrag(PointerEventData eventData)
	{
		Vector2 pos;
		RectTransformUtility.ScreenPointToLocalPointInRectangle(
			parentRectTransform,
			eventData.position, 
			eventData.pressEventCamera,
			out pos);
		(transform as RectTransform).anchoredPosition = pos;
	}
	public void OnEndDrag(PointerEventData eventData)
	{
		GameObject curEnter = eventData.pointerEnter;
		if(curEnter == null)
		{
			transform.position = beforpos;
		}
		else
		{	
			switch (curEnter.tag) 
			{
				case "skill_box":
				  transform.position = curEnter.transform.position;
				  break;
				default:
				  transform.position = beforpos;
				  break;
			}
		}
		canvasGroup.blocksRaycasts = true;
	}

	public void OnPointerExit(PointerEventData eventData)
	{
		light_skill.SetActive(false);
	}
	public void OnPointerEnter(PointerEventData eventData)
    {
    	if (Input.GetMouseButton(1)) 
    	{
    		if (skill != null) 
			{
	    		skill.auto_use = !skill.auto_use;
	    	}
    	}
    	light_skill.SetActive(true);
    }
}
